/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.pocketsweet.chat.ui.activity;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.Chronometer.OnChronometerTickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVInstallation;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVPush;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.avos.avoscloud.GetCallback;
import com.avos.avoscloud.RefreshCallback;
import com.avos.avoscloud.SaveCallback;
import com.easemob.chat.EMCallStateChangeListener;
import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EMServiceNotReadyException;
import com.pocketsweet.C;
import com.pocketsweet.R;
import com.pocketsweet.model.MLCallRecord;
import com.pocketsweet.model.MLCustomizationRecord;
import com.pocketsweet.model.MLUser;
import com.pocketsweet.service.UserService;
import com.pocketsweet.ui.LoverInvited;
import com.pocketsweet.ui.Main;
import com.pocketsweet.utils.StringUtils;
import com.pocketsweet.utils.ToolKits;

/**
 * 语音通话页面
 * 
 */
public class VoiceCallActivity extends CallActivity implements OnClickListener {
	private RelativeLayout comingBtnContainer;
	private Button hangupBtn;
	private Button refuseBtn;
	private Button answerBtn;
	private ImageView muteImage;
	private ImageView swing_card;
	private ImageView handsFreeImage;

	private boolean isMuteState;
	private boolean isHandsfreeState;

	private TextView callStateTextView;
	private int streamID;
	private boolean endCallTriggerByMe = false;
	private Handler handler = new Handler();
	private TextView nickTextView;
	private TextView durationTextView;
	private TextView tv_isCustomazition;
	private TextView tv_price;
	private Chronometer chronometer;
	String st1;
	private boolean isAnswered;
	private RelativeLayout voiceContronlLayout;
	static boolean isCustomazition = false;
	private MLCustomizationRecord curCunstomaziton;
	String str;
	private AVQuery<MLCustomizationRecord> query;
	double cost = 0;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		if (savedInstanceState != null) {
			finish();
			return;
		}
		setContentView(R.layout.activity_voice_call);

		comingBtnContainer = (RelativeLayout) findViewById(R.id.ll_coming_call);

		refuseBtn = (Button) findViewById(R.id.btn_refuse_call);
		answerBtn = (Button) findViewById(R.id.btn_answer_call);
		hangupBtn = (Button) findViewById(R.id.btn_hangup_call);

		swing_card = (ImageView) findViewById(R.id.swing_card);
		muteImage = (ImageView) findViewById(R.id.iv_mute);
		handsFreeImage = (ImageView) findViewById(R.id.iv_handsfree);
		callStateTextView = (TextView) findViewById(R.id.tv_call_state);
		nickTextView = (TextView) findViewById(R.id.tv_nick);
		durationTextView = (TextView) findViewById(R.id.tv_calling_duration);
		tv_price = (TextView) findViewById(R.id.tv_price);
		tv_isCustomazition = (TextView) findViewById(R.id.tv_isCustomazition);
		chronometer = (Chronometer) findViewById(R.id.chronometer);
		voiceContronlLayout = (RelativeLayout) findViewById(R.id.ll_voice_control);
		refuseBtn.setOnClickListener(this);
		answerBtn.setOnClickListener(this);
		hangupBtn.setOnClickListener(this);
		muteImage.setOnClickListener(this);
		handsFreeImage.setOnClickListener(this);

		getWindow().addFlags(
				WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
						| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
						| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
						| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

		// 注册语音电话的状态的监听
		addCallStateListener();
		msgid = UUID.randomUUID().toString();

		username = getIntent().getStringExtra("username");
		nickname = getIntent().getStringExtra("nickname");
		avatar = getIntent().getStringExtra("avatar");
		curDateID = getIntent().getStringExtra("curDateID");
		charge = getIntent().getDoubleExtra("charge", 0);
		isCustomazition = getIntent().getBooleanExtra("isCustomazition", false);
		curUser = UserService.getCurrentUser();
		balance = curUser.getBalance();

		if (!StringUtils.isEmpty(avatar)) {
			UserService.displayAvatar(avatar, swing_card);
		}
		// 语音电话是否为接收的
		isInComingCall = getIntent().getBooleanExtra("isComingCall", false);

		// 设置通话人
		nickTextView.setText(nickname);
		if (!isInComingCall) {// 拨打电话
			soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
			outgoing = soundPool.load(this, R.raw.outgoing, 1);

			comingBtnContainer.setVisibility(View.INVISIBLE);
			voiceContronlLayout.setVisibility(View.VISIBLE);
			st1 = getResources()
					.getString(R.string.Are_connected_to_each_other);
			callStateTextView.setText(st1);
			handler.postDelayed(new Runnable() {
				public void run() {
					streamID = playMakeCallSounds();
				}
			}, 300);
			try {
				// 拨打语音电话
				EMChatManager.getInstance().makeVoiceCall(username);
				// 发送通知
				AVQuery pushQuery = AVInstallation.getQuery();
				pushQuery.whereEqualTo("channels", username);
				AVPush push = new AVPush();
				push.setQuery(pushQuery);
				JSONObject data;
				try {
					data = new JSONObject("{\"alert\": \""
							+ curUser.getNickname()
							+ "请求与你通话\", \"sound\": \"default\",\"action\": \"com.pocketsweet.NEW__PUSH\"}");
					push.setData(data);

					push.sendInBackground();

				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			} catch (EMServiceNotReadyException e) {
				e.printStackTrace();
				final String st2 = getResources().getString(
						R.string.Is_not_yet_connected_to_the_server);
				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText(VoiceCallActivity.this, st2, 0).show();
					}
				});
			}
		} else { // 有电话进来
			voiceContronlLayout.setVisibility(View.GONE);
			Uri ringUri = RingtoneManager
					.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
			audioManager.setMode(AudioManager.MODE_RINGTONE);
			audioManager.setSpeakerphoneOn(true);
			ringtone = RingtoneManager.getRingtone(this, ringUri);
			ringtone.play();

		}
		// 如果是定制，呼出
		if (isCustomazition == true && isInComingCall == false) {
			curCunstomaziton = Main.record;
			totaltime = 0;
			charge = 0.2;
			cost = 0;
			chronometer
					.setOnChronometerTickListener(new OnChronometerTickListener() {

						@Override
						public void onChronometerTick(Chronometer chronometer) {
							String time = chronometer.getText().toString();
							String str = time.substring(time.length() - 3,
									time.length());
							// 每一分钟前开始扣费
							// Log.e("==balance1", String.valueOf(balance));
							if (":01".equals(str)) {
								totaltime += 1;
								cost += charge;
								if (totaltime == 1) {
									Intent intent = new Intent();
									intent.setAction(Main.ACTION_NEW_INVITED);
									VoiceCallActivity.this.sendBroadcast(intent);
									if (curCunstomaziton != null) {
										MLUser mlUser = new MLUser();
										mlUser.setObjectId(UserService
												.getCurrentUserId());
										curCunstomaziton.setTime(totaltime);
										curCunstomaziton.setCost(cost);
										curCunstomaziton.setWinner(mlUser);
										curCunstomaziton
												.setStatus(C.LOVE_CALL_FINISH);
										curCunstomaziton
												.saveInBackground(new SaveCallback() {

													@Override
													public void done(
															AVException arg0) {
														if (arg0 != null) {
//															Log.e("==ee",
//																	arg0.getMessage());
														}
													}
												});
									} else {
//										Log.e("==ee", "nbulllllllllll");

									}
								} else if (totaltime != 1) {
									if (curCunstomaziton != null) {
										// call
										// 的自增
										curCunstomaziton.increment("time");
										BigDecimal balanceFormat = new BigDecimal(
												cost).setScale(2,
												BigDecimal.ROUND_HALF_UP);
										cost = balanceFormat.doubleValue();
										curCunstomaziton.setCost(cost);
										curCunstomaziton
												.setStatus(C.LOVE_CALL_FINISH);
										curCunstomaziton.saveInBackground();
										// Log.e("==totaltime",
										// "=balance totaltime is create2");

									}
								}
							}
						}
					});

		}
		// 如果是定制
		else if (isCustomazition == true && isInComingCall) {
			Main.isConnect = true;
			curCunstomaziton = null;
			totaltime = 0;
			totalCost = 0;
			tv_isCustomazition.setVisibility(View.VISIBLE);
			tv_price.setVisibility(View.VISIBLE);
			charge = 0.2;
			query = new AVQuery<MLCustomizationRecord>("MLCustomizationRecord");
			chronometer
					.setOnChronometerTickListener(new OnChronometerTickListener() {

						@Override
						public void onChronometerTick(Chronometer chronometer) {
							String time = chronometer.getText().toString();
							String str = time.substring(time.length() - 3,
									time.length());
							// 每一分钟前开始扣费
							// Log.e("==balance1", String.valueOf(balance));
							if (":01".equals(str)) {
								UserService
										.getCurrentUser()
										.refreshInBackground(
												new RefreshCallback<AVObject>() {

													@Override
													public void done(
															AVObject arg0,
															AVException arg1) {
														if (arg1 == null) {
															curUser = UserService
																	.getCurrentUser();
															balance = curUser
																	.getBalance();
															if (balance < charge) { // 余额不足挂断
																ToolKits.toast(
																		VoiceCallActivity.this,
																		"您的余额不足");
																if (soundPool != null)
																	soundPool
																			.stop(streamID);
																endCallTriggerByMe = true;
																try {
																	EMChatManager
																			.getInstance()
																			.endCall();
																} catch (Exception e) {
																	e.printStackTrace();
																	saveCallRecord(0);
																	finish();
																}
															} else {
																balance = balance
																		- charge;
																totaltime += 1;
																totalCost += charge;
																BigDecimal balanceFormat = new BigDecimal(
																		balance)
																		.setScale(
																				2,
																				BigDecimal.ROUND_HALF_UP);
																balance = balanceFormat
																		.doubleValue();
																curUser.setBalance(balance);
																curUser.saveInBackground(new SaveCallback() {

																	@Override
																	public void done(
																			AVException e) {
																		if (e == null) {
																			// 调用云代码给对方钱
																			Map<String, Object> params = new HashMap<String, Object>();
																			params.put(
																					"userId",
																					username);
																			params.put(
																					"price",
																					charge);
																			AVCloud.callFunctionInBackground(
																					"newTransferAccount",
																					params,
																					new FunctionCallback<String>() {

																						@Override
																						public void done(
																								String arg0,
																								AVException arg1) {
																							// Log.e("==zhuanggggg",
																							// "result:"
																							// +
																							// arg0);
																						}
																					});
																		}
																	}
																});

															}
														}
													}
												});
							}

						}
					});

		} else

		// 设置监听
		if (charge != 0) {
			totaltime = 0;
			totalCost = 0;
			chronometer
					.setOnChronometerTickListener(new OnChronometerTickListener() {

						@Override
						public void onChronometerTick(Chronometer chronometer) {
							String time = chronometer.getText().toString();
							str = time.substring(time.length() - 3,
									time.length());
							// 每一分钟前开始扣费
							// Log.e("==balance1", String.valueOf(balance));
							if (":01".equals(str)) {
								UserService
										.getCurrentUser()
										.refreshInBackground(
												new RefreshCallback<AVObject>() {

													@Override
													public void done(
															AVObject arg0,
															AVException arg1) {
														if (arg1 == null) {
															curUser = UserService
																	.getCurrentUser();
															balance = curUser
																	.getBalance();
															if (balance < charge) { // 余额不足挂断
																ToolKits.toast(
																		VoiceCallActivity.this,
																		"您的余额不足");
																// Log.e("==balance2",
																// String.valueOf(balance));
																if (soundPool != null)
																	soundPool
																			.stop(streamID);
																endCallTriggerByMe = true;
																try {
																	EMChatManager
																			.getInstance()
																			.endCall();
																} catch (Exception e) {
																	e.printStackTrace();
																	saveCallRecord(0);
																	finish();
																}
															} else {
																balance = balance
																		- charge;
																// Log.e("==balance3",
																// "=balance"+String.valueOf(balance));
																// Log.e("==totaltime",
																// "=balance"+String.valueOf(totaltime));
																totaltime += 1;
																totalCost += charge;
																if (totaltime == 1) {
																	// 第一次时候生成一条电话记录，并开始自增
																	// Log.e("==totaltime",
																	// "=balance totaltime is 0");

																	AVQuery<MLUser> query = new AVQuery<MLUser>(
																			"_User");
																	query.getInBackground(
																			username,
																			new GetCallback<MLUser>() {

																				@Override
																				public void done(
																						final MLUser user,
																						AVException e) {
																					MLUser toUser = new MLUser();
																					toUser.setObjectId(user
																							.getObjectId());
																					call = new MLCallRecord();
																					call.increment("time");
																					call.setCost(charge);
																					call.setUser(toUser);
																					call.setSponsor(curUser);
																					call.saveInBackground();
																					// Log.e("==totaltime",
																					// "=balance totaltime is create");

																				}
																			});
																}
																BigDecimal balanceFormat = new BigDecimal(
																		balance)
																		.setScale(
																				2,
																				BigDecimal.ROUND_HALF_UP);
																balance = balanceFormat
																		.doubleValue();
																curUser.setBalance(balance);
																// UserService
																// .getCurrentUser()
																// .setBalance(
																// balance);
																curUser.saveInBackground(new SaveCallback() {

																	@Override
																	public void done(
																			AVException e) {
																		// TODO
																		// Auto-generated
																		// method
																		// stub
																		if (e == null) {
																			if (totaltime != 1) {
																				if (call != null) {
																					// call
																					// 的自增
																					call.increment("time");
																					BigDecimal balanceFormat = new BigDecimal(
																							totalCost)
																							.setScale(
																									2,
																									BigDecimal.ROUND_HALF_UP);
																					totalCost = balanceFormat
																							.doubleValue();
																					call.setCost(totalCost);
																					call.saveInBackground();
																					// Log.e("==totaltime",
																					// "=balance totaltime is create2");

																				}
																			}

																			// 调用云代码给对方钱
																			Map<String, Object> params = new HashMap<String, Object>();
																			params.put(
																					"userId",
																					username);
																			params.put(
																					"price",
																					charge);
																			AVCloud.callFunctionInBackground(
																					"newTransferAccount",
																					params,
																					new FunctionCallback<String>() {

																						@Override
																						public void done(
																								String arg0,
																								AVException arg1) {
																							// Log.e("==zhuanggggg",
																							// "result:"
																							// +
																							// arg0);
																						}
																					});
																		}
																	}
																});

															}

														}
													}
												});
							}
						}
					});
		}
	}

	/**
	 * 设置电话监听
	 */
	void addCallStateListener() {
		callStateListener = new EMCallStateChangeListener() {

			@Override
			public void onCallStateChanged(CallState callState, CallError error) {
				// Message msg = handler.obtainMessage();
				switch (callState) {

				case CONNECTING: // 正在连接对方
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							callStateTextView.setText(st1);
						}

					});
					break;
				case CONNECTED: // 双方已经建立连接
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							// TODO Auto-generated method stub
							String st3 = getResources().getString(
									R.string.have_connected_with);
							callStateTextView.setText(st3);

						}

					});
					break;

				case ACCEPTED: // 电话接通成功
					runOnUiThread(new Runnable() {

						@Override
						public void run() {
							try {
								if (soundPool != null)
									soundPool.stop(streamID);
							} catch (Exception e) {
							}
							closeSpeakerOn();
							chronometer.setVisibility(View.VISIBLE);
							chronometer.setBase(SystemClock.elapsedRealtime());
							// 开始记时
							chronometer.start();
							String str4 = getResources().getString(
									R.string.In_the_call);
							callStateTextView.setText(str4);
							callingState = CallingState.NORMAL;
							// 将约会状态改为成功
							if (Main.customazitonLoverId != null) {// 把定制恋人的customazitonLoverId改为空，下次打就不是定制了
								Main.customazitonLoverId = null;
							}

						}

					});
					break;
				case DISCONNNECTED: // 电话断了
					final CallError fError = error;
					runOnUiThread(new Runnable() {
						private void postDelayedCloseMsg() {
							handler.postDelayed(new Runnable() {

								@Override
								public void run() {
									if (UserService.getCurrentUser().getType() != C.USER_TYPE_NORMAL) {
										UserService.getCurrentUser()
												.refreshInBackground(null);
									}
									saveCallRecord(0);
									Animation animation = new AlphaAnimation(
											1.0f, 0.0f);
									animation.setDuration(800);
									findViewById(R.id.root_layout)
											.startAnimation(animation);
									finish();
								}

							}, 200);
						}

						@Override
						public void run() {
							chronometer.stop();
							callDruationText = chronometer.getText().toString();
							String st2 = getResources().getString(
									R.string.The_other_party_refused_to_accept);
							String st3 = getResources().getString(
									R.string.Connection_failure);
							String st4 = getResources().getString(
									R.string.The_other_party_is_not_online);
							String st5 = getResources().getString(
									R.string.The_other_is_on_the_phone_please);

							String st6 = getResources()
									.getString(
											R.string.The_other_party_did_not_answer_new);
							String st7 = getResources().getString(
									R.string.hang_up);
							String st8 = getResources().getString(
									R.string.The_other_is_hang_up);

							String st9 = getResources().getString(
									R.string.did_not_answer);
							String st10 = getResources().getString(
									R.string.Has_been_cancelled);
							String st11 = getResources().getString(
									R.string.hang_up);

							if (fError == CallError.REJECTED) {
								callingState = CallingState.BEREFUESD;
								callStateTextView.setText(st2);
							} else if (fError == CallError.ERROR_TRANSPORT) {
								callStateTextView.setText(st3);
							} else if (fError == CallError.ERROR_INAVAILABLE) {
								callingState = CallingState.OFFLINE;
								callStateTextView.setText(st4);
							} else if (fError == CallError.ERROR_BUSY) {
								callingState = CallingState.BUSY;
								callStateTextView.setText(st5);
							} else if (fError == CallError.ERROR_NORESPONSE) {
								callingState = CallingState.NORESPONSE;
								callStateTextView.setText(st6);
							} else {
								if (isAnswered) {
									callingState = CallingState.NORMAL;
									if (endCallTriggerByMe) {
										callStateTextView.setText(st7);
									} else {
										callStateTextView.setText(st8);
									}
								} else {
									if (isInComingCall) {
										callingState = CallingState.UNANSWERED;
										callStateTextView.setText(st9);
									} else {
										if (callingState != CallingState.NORMAL) {
											callingState = CallingState.CANCED;
											callStateTextView.setText(st10);
										} else {
											callStateTextView.setText(st11);
										}
									}
								}
							}
							postDelayedCloseMsg();
						}

					});

					break;

				default:
					break;
				}

			}
		};
		EMChatManager.getInstance().addVoiceCallStateChangeListener(
				callStateListener);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_refuse_call: // 拒绝接听
			if (ringtone != null)
				ringtone.stop();
			try {
				EMChatManager.getInstance().rejectCall();
			} catch (Exception e1) {
				e1.printStackTrace();
				saveCallRecord(0);
				finish();
			}
			callingState = CallingState.REFUESD;
			break;

		case R.id.btn_answer_call: // 接听电话
			comingBtnContainer.setVisibility(View.GONE);
			voiceContronlLayout.setVisibility(View.VISIBLE);
			if (ringtone != null)
				ringtone.stop();
			closeSpeakerOn();
			if (isInComingCall) {
				try {
					isAnswered = true;
					EMChatManager.getInstance().answerCall();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					saveCallRecord(0);
					finish();
				}
			}
			break;

		case R.id.btn_hangup_call: // 挂断电话
			if (soundPool != null)
				soundPool.stop(streamID);
			endCallTriggerByMe = true;
			try {
				EMChatManager.getInstance().endCall();
			} catch (Exception e) {
				e.printStackTrace();
				saveCallRecord(0);
				finish();
			}
			break;

		case R.id.iv_mute: // 静音开关
			if (isMuteState) {
				// 关闭静音
				muteImage.setImageResource(R.drawable.icon_mute_normal);
				audioManager.setMicrophoneMute(false);
				isMuteState = false;
			} else {
				// 打开静音
				muteImage.setImageResource(R.drawable.icon_mute_on);
				audioManager.setMicrophoneMute(true);
				isMuteState = true;
			}
			break;
		case R.id.iv_handsfree: // 免提开关
			if (isHandsfreeState) {
				// 关闭免提
				handsFreeImage.setImageResource(R.drawable.icon_speaker_normal);
				closeSpeakerOn();
				isHandsfreeState = false;
			} else {
				handsFreeImage.setImageResource(R.drawable.icon_speaker_on);
				openSpeakerOn();
				isHandsfreeState = true;
			}
			break;
		default:
			break;
		}
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
	}

	@Override
	public void onBackPressed() {
		EMChatManager.getInstance().endCall();
		callDruationText = chronometer.getText().toString();
		saveCallRecord(0);
		finish();
	}

}
